package com.example.mpandroidchartdemo;

import android.graphics.Color;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.github.mikephil.charting.charts.ScatterChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.ScatterData;
import com.github.mikephil.charting.data.ScatterDataSet;

import java.util.ArrayList;
import java.util.List;

public class ScatterChartActivity extends AppCompatActivity {

    private ScatterChart mScatterChart;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.scatter_chart_activity);
        initView();
    }

    private void initView(){
        mScatterChart = findViewById(R.id.scatter_chart);
        mScatterChart.getDescription().setEnabled(false);
//        mScatterChart.setTouchEnabled(true); // 开启/关闭图表交互
        // 标签
        Legend legend = mScatterChart.getLegend();
        legend.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
        legend.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT);
        legend.setOrientation(Legend.LegendOrientation.VERTICAL);
        legend.setDrawInside(false); // 标签在图表外
        legend.setXOffset(5F);
        mScatterChart.animateX(3000);
        // 添加数据
        setData();
    }

    private void setData(){
        List<Entry> list1 = new ArrayList<>();
        List<Entry> list2 = new ArrayList<>();
        List<Entry> list3 = new ArrayList<>();

        for (int i = 0; i < 10; i++) {
            float val = (float) ((Math.random() * 10) + 3);
            list1.add(new Entry(i, val));
        }
        for (int i = 0; i < 10; i++) {
            float val = (float) ((Math.random() * 10) + 3);
            list2.add(new Entry(i + 0.33F, val));
        }
        for (int i = 0; i < 10; i++) {
            float val = (float) ((Math.random() * 10) + 3);
            list3.add(new Entry(i + 0.66F,val));
        }

        ScatterDataSet scatterDataSet1 = new ScatterDataSet(list1,"优秀");
        scatterDataSet1.setColor(Color.RED);
        scatterDataSet1.setScatterShape(ScatterChart.ScatterShape.SQUARE);
        ScatterDataSet scatterDataSet2 = new ScatterDataSet(list2,"及格");
        scatterDataSet2.setColor(Color.BLUE);
        scatterDataSet2.setScatterShape(ScatterChart.ScatterShape.CIRCLE);
        scatterDataSet2.setScatterShapeHoleRadius(3F);
        ScatterDataSet scatterDataSet3 = new ScatterDataSet(list3,"不及格");
        scatterDataSet3.setColor(Color.GREEN);
        scatterDataSet3.setScatterShape(ScatterChart.ScatterShape.CROSS);

        ScatterData scatterData = new ScatterData(scatterDataSet1);
        scatterData.addDataSet(scatterDataSet2);
        scatterData.addDataSet(scatterDataSet3);
        mScatterChart.setData(scatterData);
    }
}
